import * as signalR from "@microsoft/signalr";
import { getToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'

let message;
let host = import.meta.env.VITE_APP_REMOTE
const hubConnection = new signalR.HubConnectionBuilder()
    .withUrl(`${host}/userHub`, {
        accessTokenFactory: () => getToken(),
    })
    .withAutomaticReconnect([0, 1000])
    .build();

signalR.HubConnectionState.Connecting

//服务器断开连接
hubConnection.onclose(async (error) => {
    message.close();
    var msg = `和服务器断开连接，请刷新页面`
    message = ElMessage({
        message: msg,
        type: 'error',
        plain: true,
        duration: 0
    })
    // 如果希望在连接断开时尝试重连，可以手动调用重连逻辑：
    setTimeout(() => {
        startConnection();
    }, 5000);  // 延迟5秒重连
});


hubConnection.onreconnecting((error) => {
    var msg = `和服务器断开连接，正尝试重新连接......`
    message = ElMessage({
        message: msg,
        type: 'warning',
        plain: true,
        duration: 0
    })

});

hubConnection.onreconnected((connectionId) => {
    message.close();
    var msg = `服务器连接成功`
    ElMessage({
        message: msg,
        type: "success",
        plain: true,
    })
    console.log("SignalR 连接已重连，连接ID:", connectionId);
});

export const startConnection = async () => {
    // 如果用户没有登录（即没有 token），等待用户登录
    var token = getToken()
    if (!token) {
        console.log("用户未登录，正在等待...");
        // 可以监听用户登录的事件或者定时检查
        const interval = setInterval(() => {
            token = getToken();  // 获取最新的 token
            if (token) {
                clearInterval(interval);  // 停止检查
                console.log("用户已登录，正在连接 SignalR...");
                startConnection();  // 用户登录后启动连接
            }
        }, 1000);  // 每秒检查一次

        return;
    }
    try {
        await hubConnection.start();
        if (message) message.close();
        var msg = `服务器连接成功`
        ElMessage({
            message: msg,
            type: "success",
            plain: true,
        })
        console.log("SignalR 已连接");
        // notifySignIn();
    } catch (err) {
        console.error("SignalR 连接出现异常:", err);
        setTimeout(startConnection, 5000); // 重连
    }
};

// 通知后端用户登录成功
export const notifySignIn = async () => {
    const token = getToken();
    console.log(hubConnection.connectionId);
    try {
        await hubConnection.invoke("OnSignIn");
    } catch (err) {
        console.error("登录通知失败:", err);
    }
};

export const onUserConnected = (callback) => {
    hubConnection.on("UserConnected", callback);
};

export const onUserDisconnected = (callback) => {
    hubConnection.on("UserDisconnected", callback);
};

export const onUserSignOn = (callback) => {
    hubConnection.on("UserSignOn", callback);
}

export const disconnectConnection = async () => {
    try {
        await hubConnection.stop();
        console.log("SignalR 断开连接");
    } catch (err) {
        console.error("SignalR 断开连接异常:", err);
    }
};


export { hubConnection as appHub };
